const PersonService = require("../services/PersonService");
const JWT = require("../utils/JWT");
const PersonController = {
  addPerson: async (req, res) => {
    try {
      let avatar = req.file
        ? `/uploads/${req.file.filename}`
        : "/images/default.png";
      console.log(req.body, avatar);
      const data = await PersonService.addPerson(req.body, avatar);
      console.log(data);
      res.send(JSON.stringify({ status: "success", data }));
    } catch (err) {
      console.warn(err);
      res.send(JSON.stringify({ status: "error", err }));
    }
  },
  updatePerson: async (req, res) => {
    console.log(req.body);
    try {
      const data = await PersonService.updatePerson(req.body._id, req.body);
      console.log(data);
      res.send(JSON.stringify({ status: "success", data }));
    } catch (err) {
      console.warn(err);
      res.send(JSON.stringify({ status: "error", err }));
    }
  },
  getPersonOrList: async (req, res) => {
    // cookie-parser 基本使用
    // https://blog.csdn.net/weixin_44714325/article/details/113933831
    // console.log(req.cookies);
    // console.log(req.query);
    const _id = req.params?.id;
    // console.log('_id', _id, {_id})
    try {
      const data = _id
        ? await PersonService.getPersonOrList(_id)
        : await PersonService.getPersonOrList(
            null,
            req.query.page,
            req.query.limit
          );
      //   console.log(data);
      res.send(JSON.stringify({ status: "success", data }));
    } catch (err) {
      console.warn(err);
      res.send(JSON.stringify({ status: "error", err }));
    }
  },
  delPerson: async (req, res) => {
    console.log(req.params);
    try {
      const data = await PersonService.delPerson(req.params.id);
      console.log(data);
      res.send(JSON.stringify({ status: "success", data }));
    } catch (err) {
      console.warn(err);
      res.send(JSON.stringify({ status: "error", err }));
    }
  },
  login: async (req, res) => {
    // console.log(req.body);
    try {
      const data = await PersonService.login(req.body);
      const token = JWT.encode(
        { _id: data._id, username: data.username },
        "1h"
      );
      // console.log(token)
      res.header("authorization", token); // 接口从头部返回token
      res.send(JSON.stringify({ status: "success", data }));
    } catch (err) {
      console.warn(err);
      res.send(JSON.stringify({ status: "error", err }));
    }
  },
  logout: (req, res) => {
    // 销毁 session
    req.session.destroy(() => {
      res.send(JSON.stringify({ status: "success" }));
    });
  },
};

module.exports = PersonController;
